<script lang="ts" setup>
import type { FileUploadItem } from '../../components/FileUploader/types';

import type { FileInfo, ShareItem as ShareInfo } from '#/api/openapi';

import { computed, nextTick, ref } from 'vue';

import { usePreferences } from '@vben/preferences';

import { FileOutlined as File } from '@ant-design/icons-vue';
import {
  CheckOne,
  Code,
  Delete,
  FileText,
  MessageOne,
  Plus,
  PreviewOpen,
  Time,
  Upload,
} from '@icon-park/vue-next';
import { message } from 'ant-design-vue';

import { client } from '#/api';
import { confirm } from '#/components/global-dialog';
import { copyShareCode } from '#/utils/copy';
import { downloadFile } from '#/utils/download';
import { getFileIcon } from '#/utils/icon';

import UploadDialog from '../../components/FileUploader/UploadDialog.vue';
import MessageEditDialog from '../../components/MessageManager/MessageEditDialog.vue';
import ShareInfoDialog from '../../components/ShareDialog/ShareInfoDialog.vue';
import UploadCompleteDialog from '../../components/UploadCompleteDialog/UploadCompleteDialog.vue';
import { useUploadHistoryStore } from '../../store/upload-history';

// 消息数据类型 - 兼容组件和API
interface MessageItem {
  id: string;
  content: string;
  timestamp: string;
}

const { isDark } = usePreferences();
const uploadHistoryStore = useUploadHistoryStore();

// 从 store 获取历史记录
const uploadHistory = computed(() => uploadHistoryStore.getAllHistory);

// 统计数据 - 从 store 获取
const stats = computed(() => {
  const storeStats = uploadHistoryStore.getStats;
  return {
    ...storeStats,
    totalSize: formatFileSize(storeStats.totalSize),
  };
});

// 控制上传对话框显示状态
const isUploadDialogOpen = ref(false);
const isUploading = ref(false);

// 控制消息编辑对话框显示状态
const isMessageDialogOpen = ref(false);
const currentUploadItemId = ref<string>('');
const currentShareCode = ref<string>('');
const currentEditToken = ref<string>('');

// 控制详情对话框显示状态
const isShareInfoDialogOpen = ref(false);
const currentShareInfo = ref<ShareInfo>();

// 控制上传完成对话框显示状态
const isUploadCompleteDialogOpen = ref(false);
const uploadCompleteData = ref<{
  averageSpeed?: number;
  items: FileUploadItem[];
  shareCode?: string;
  totalSize?: number;
}>({
  items: [],
});

// UploadDialog组件引用
const uploadDialogRef = ref();

// 打开上传对话框
const openUploadDialog = () => {
  isUploadDialogOpen.value = true;
  // 在下一个tick后重置对话框内容，确保组件已挂载
  nextTick(() => {
    uploadDialogRef.value?.resetDialog();
  });
};

// 关闭上传对话框
const closeUploadDialog = () => {
  // 如果正在上传，显示警告但不关闭对话框
  if (isUploading.value) {
    message.warning({
      content: '文件正在上传中，请等待上传完成后再关闭',
      duration: 3,
    });
    return;
  }
  isUploadDialogOpen.value = false;
};

// 打开消息管理对话框
const openMessageDialog = async (uploadItemId: string) => {
  currentUploadItemId.value = uploadItemId;

  // 从上传历史中找到对应的分享记录
  const historyItem = uploadHistory.value.find(
    (item) => item.id === uploadItemId,
  );
  if (!historyItem || !historyItem.shareCode) {
    message.error('找不到对应的分享记录或分享码');
    return;
  }

  currentShareCode.value = historyItem.shareCode;
  // 使用存储的editToken，如果没有则提示用户
  currentEditToken.value = historyItem.editToken || '';

  if (!historyItem.editToken) {
    message.warning('此分享记录缺少编辑令牌，可能无法进行编辑操作');
  }

  isMessageDialogOpen.value = true;
};

// 关闭消息管理对话框
const closeMessageDialog = () => {
  isMessageDialogOpen.value = false;
};

// 打开详情对话框
const openShareInfoDialog = async (
  item: (typeof uploadHistory.value)[number],
) => {
  // 将本地历史记录数据转换为ShareInfo格式
  const shareInfo: ShareInfo = {
    id: item.backendId || 0,
    code: item.shareCode,
    createTime: new Date(item.uploadTime).toISOString(),
    expiryTime: item.expiryTime
      ? new Date(item.expiryTime).toISOString()
      : undefined,
    files: item.files.map(
      (file): FileInfo => ({
        id: Number.parseInt(file.id) || 0,
        fileName: file.name,
        fileSize: file.size,
        uploadTime: new Date(item.uploadTime).toISOString(),
        downloadCount: 0, // 本地历史记录中没有下载次数信息
      }),
    ),
    messages: item.message
      ? [
          {
            id: 1,
            content: item.message,
            createdAt: new Date(item.uploadTime).toISOString(),
          },
        ]
      : [],
  };
  currentShareInfo.value = shareInfo;
  if (shareInfo.code) {
    const { data } = await client.shareItem.getShareItemById(shareInfo.code);
    if (data.code && data.files) {
      currentShareInfo.value = data;
    }
  }
  isShareInfoDialogOpen.value = true;
};

// 关闭详情对话框
const closeShareInfoDialog = () => {
  isShareInfoDialogOpen.value = false;
  currentShareInfo.value = undefined;
};

// 打开上传完成对话框
const openUploadCompleteDialog = (
  items: FileUploadItem[],
  shareCode?: string,
  averageSpeed?: number,
  totalSize?: number,
) => {
  uploadCompleteData.value = {
    items,
    shareCode,
    averageSpeed,
    totalSize,
  };
  isUploadCompleteDialogOpen.value = true;
};

// 关闭上传完成对话框
const closeUploadCompleteDialog = () => {
  isUploadCompleteDialogOpen.value = false;
  uploadCompleteData.value = { items: [] };
};

// 从上传完成对话框查看详情
const handleViewDetailsFromComplete = () => {
  // 如果有分享码，找到对应的历史记录并打开详情
  const shareCode = uploadCompleteData.value.shareCode;
  if (shareCode) {
    const historyItem = uploadHistory.value.find(
      (item) => item.shareCode === shareCode,
    );
    if (historyItem) {
      openShareInfoDialog(historyItem);
    }
  }
};

// 处理下载全部文件
const handleDownloadAll = (code: string, files: FileInfo[]) => {
  console.log('下载全部文件:', code, files);
  // 这里可以调用实际的下载API
  for (const file of files) {
    downloadFile(code, file);
  }
};

// 处理下载单个文件
const handleDownloadFile = (code: string, file: FileInfo) => {
  console.log('下载单个文件:', code, file);
  // 这里可以调用实际的下载API
  downloadFile(code, file);
};

// 处理上传完成事件
const handleDialogUploadComplete = (
  items: FileUploadItem[],
  averageSpeed?: number,
  shareInfo?: null | {
    backendId: null | number | undefined;
    editToken: null | string | undefined;
    shareCode: null | string;
  },
) => {
  // 将成功上传的文件添加到历史记录
  const successItems = items.filter((item) => item.status === 'success');

  if (successItems.length > 0) {
    // 使用从 API 返回的分享信息或生成新的分享码
    const shareCode =
      shareInfo?.shareCode || uploadHistoryStore.generateShareCode();
    const editToken = shareInfo?.editToken;
    const backendId = shareInfo?.backendId;

    // 添加到 store，传递完整的分享信息
    uploadHistoryStore.addHistoryItem(
      successItems,
      shareCode,
      undefined,
      averageSpeed,
      editToken || undefined, // 将null转换为undefined
      backendId || undefined, // 将null转换为undefined
    );

    // 计算总文件大小
    const totalSize = items.reduce((sum, item) => sum + item.size, 0);

    // 打开上传完成对话框
    openUploadCompleteDialog(items, shareCode, averageSpeed, totalSize);
  }

  closeUploadDialog();
};

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';

  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;
};

// 获取状态颜色
const getStatusColor = (status: string) => {
  switch (status) {
    case 'error': {
      return 'text-red-600';
    }
    case 'success': {
      return 'text-primary-600';
    }
    case 'uploading': {
      return 'text-blue-600';
    }
    default: {
      return 'text-gray-600';
    }
  }
};

// 获取状态图标
const getStatusIcon = (status: string) => {
  switch (status) {
    case 'error': {
      return Time;
    }
    case 'success': {
      return CheckOne;
    }
    case 'uploading': {
      return Upload;
    }
    default: {
      return File;
    }
  }
};

// 处理消息更新
const handleMessagesUpdated = (messages: MessageItem[]) => {
  // 这里可以将消息保存到服务器或本地存储
  console.log('消息已更新:', messages);
};

// 清空所有历史记录
const handleClearAllHistory = async () => {
  if (
    await confirm('确定要清空所有上传历史记录吗？此操作无法恢复！', '确认清空')
  ) {
    uploadHistoryStore.clearHistory();
    message.success({
      content: '已清空所有上传历史记录',
      duration: 3,
    });
  }
};

// 删除上传记录
const handleDeleteHistory = async (
  item: (typeof uploadHistory.value)[number],
) => {
  if (
    await confirm(
      `确定要删除分享码为 "${item.shareCode}" 的上传记录吗？删除后将无法恢复！`,
      '确认删除',
    )
  ) {
    // 从 store 中删除记录
    uploadHistoryStore.removeHistoryItem(item.id);

    // 显示成功消息
    message.success({
      content: `已删除分享码为 "${item.shareCode}" 的上传记录`,
      duration: 3,
    });
  }
};
</script>

<template>
  <div class="px-auto mx-auto max-w-7xl py-8">
    <div class="mb-8 text-center">
      <h1 class="mb-3 text-4xl font-bold">文件传输中心</h1>
      <p class="text-lg text-gray-600 dark:text-gray-300">
        文件上传历史记录和管理
      </p>
    </div>
    <div
      class="bg-background text-foreground mx-auto min-h-screen p-6"
      :data-theme="isDark ? 'dark' : 'light'"
    >
      <!-- 统计卡片 -->
      <div class="mx-auto mb-6 flex items-center justify-between">
        <div class="mb-8 grid grid-cols-1 gap-4 md:grid-cols-3">
          <div class="border-border bg-card rounded-lg border p-4 shadow-sm">
            <div class="flex items-center justify-between">
              <div class="mr-2">
                <p class="text-muted-foreground text-sm">分享批次</p>
                <p class="text-primary text-2xl font-bold">{{ stats.total }}</p>
              </div>
              <FileText size="24" class="text-primary" />
            </div>
          </div>

          <div class="border-border bg-card rounded-lg border p-4 shadow-sm">
            <div class="flex items-center justify-between">
              <div>
                <p class="text-muted-foreground text-sm">上传成功</p>
                <p class="text-primary text-2xl font-bold">
                  {{ stats.success }}
                </p>
              </div>
              <CheckOne class="text-primary" size="24" />
            </div>
          </div>

          <div class="border-border bg-card rounded-lg border p-4 shadow-sm">
            <div class="flex items-center justify-between">
              <div class="mr-1">
                <p class="text-muted-foreground text-sm">总大小</p>
                <p class="text-primary text-2xl font-bold">
                  {{ stats.totalSize }}
                </p>
              </div>
              <Upload size="24" class="text-primary" />
            </div>
          </div>
        </div>
        <div class="flex flex-col gap-3">
          <Button appearance="primary" size="large" @click="openUploadDialog">
            <div class="flex items-center gap-2">
              <Plus theme="outline" size="18" fill="currentColor" />
              <span>新增上传</span>
            </div>
          </Button>
        </div>
      </div>
      <!-- 上传历史 -->
      <div class="border-border bg-card rounded-lg border p-6 shadow-sm">
        <div class="mb-4 flex items-center justify-between">
          <h3 class="text-lg font-semibold">上传历史</h3>

          <div class="text-muted-foreground text-sm">
            <Button
              v-if="uploadHistory.length > 0"
              appearance="subtle"
              @click="handleClearAllHistory"
              class="border-red-200 text-red-600 hover:bg-red-50 dark:border-red-800 dark:text-red-400 dark:hover:bg-red-900/20"
            >
              <div class="flex items-center gap-2">
                <Delete theme="outline" size="18" fill="currentColor" />
                <span>清空历史</span>
              </div>
            </Button>
          </div>
        </div>

        <div
          v-if="uploadHistory.length === 0"
          class="text-muted-foreground py-12 text-center"
        >
          <div class="mb-4 flex justify-center">
            <FileText theme="outline" size="64" fill="#9CA3AF" />
          </div>
          <p class="mb-2 text-lg">暂无上传历史</p>
          <p class="text-sm">点击上方"新增上传"按钮开始上传文件</p>
        </div>

        <div
          v-else
          class="flex flex-col gap-4 lg:grid lg:grid-cols-2 lg:gap-6 xl:grid-cols-3"
        >
          <div
            v-for="item in uploadHistory"
            :key="item.id"
            class="bg-accent flex h-fit flex-col rounded-lg p-4 transition-all hover:shadow-md"
          >
            <!-- 分享信息头部 -->
            <div class="mb-3 flex items-center justify-between">
              <div class="flex items-center space-x-3">
                <div class="flex items-center space-x-1">
                  <component
                    :is="getStatusIcon(item.status)"
                    theme="outline"
                    size="22"
                    :fill="
                      item.status === 'success'
                        ? '#10B981'
                        : item.status === 'uploading'
                          ? '#3B82F6'
                          : '#EF4444'
                    "
                  />
                  <div>
                    <span
                      class="text-sm font-medium"
                      :class="[getStatusColor(item.status)]"
                    >
                      {{
                        item.status === 'success'
                          ? '分享成功'
                          : item.status === 'uploading'
                            ? '上传中'
                            : '分享失败'
                      }}
                    </span>
                    <div class="flex">
                      <span class="text-muted-foreground text-xs">{{
                        item.formattedTime
                      }}</span>
                    </div>
                  </div>
                </div>
              </div>
              <div class="flex items-center space-x-2">
                <!-- 删除按钮 -->
                <Tooltip content="删除此上传记录" placement="top" :delay="500">
                  <Button
                    size="small"
                    appearance="subtle"
                    @click="() => handleDeleteHistory(item)"
                    class="rounded hover:bg-red-100 dark:hover:bg-red-900/50"
                  >
                    <template #start>
                      <Delete size="16" class="text-red-500" />
                    </template>
                    <span class="text-md text-red-500">删除</span>
                  </Button>
                </Tooltip>
                <!-- 消息管理按钮 -->
                <Tooltip
                  content="管理此分享的消息"
                  placement="top"
                  :delay="500"
                >
                  <Button
                    appearance="subtle"
                    size="small"
                    @click="() => openMessageDialog(item.id)"
                    class="rounded hover:bg-blue-100 dark:hover:bg-blue-900/50"
                  >
                    <template #start>
                      <MessageOne size="16" />
                    </template>
                    <span class="text-md">消息</span>
                  </Button>
                </Tooltip>
                <Button
                  size="small"
                  appearance="subtle"
                  title="查看详情"
                  @click="() => openShareInfoDialog(item)"
                  class="rounded hover:bg-blue-100 dark:hover:bg-blue-900/50"
                >
                  <template #start>
                    <PreviewOpen size="14" />
                  </template>
                  <span class="text-md">详情</span>
                </Button>
              </div>
            </div>

            <!-- 文件列表 -->
            <div class="space-y-2">
              <div
                v-for="file in item.files"
                :key="file.id"
                class="bg-background/50 flex items-center space-x-3 rounded p-2"
              >
                <component
                  :is="getFileIcon(file.name)"
                  theme="outline"
                  size="24"
                  fill="currentColor"
                  class="text-muted-foreground flex-shrink-0"
                />
                <div class="min-w-0 flex-1">
                  <p class="truncate text-sm font-medium">{{ file.name }}</p>
                  <p class="text-muted-foreground text-xs">
                    {{ formatFileSize(file.size) }}
                  </p>

                  <!-- 单个文件的上传进度（仅对正在上传的文件显示） -->
                  <div
                    v-if="file.status === 'uploading' && file.progress"
                    class="mt-1"
                  >
                    <div class="mb-1 flex items-center justify-between text-xs">
                      <span class="text-blue-600">上传中...</span>
                      <span class="text-blue-600">{{ file.progress }}%</span>
                    </div>
                    <div class="h-1 w-full rounded-full bg-gray-200">
                      <div
                        class="h-1 rounded-full bg-blue-600 transition-all duration-300"
                        :style="{ width: `${file.progress}%` }"
                      ></div>
                    </div>
                  </div>
                </div>

                <div class="flex items-center space-x-1">
                  <component
                    :is="getStatusIcon(file.status)"
                    theme="outline"
                    size="18"
                    :fill="
                      file.status === 'success'
                        ? '#10B981'
                        : file.status === 'uploading'
                          ? '#3B82F6'
                          : '#EF4444'
                    "
                  />
                </div>
              </div>
            </div>

            <!-- 总进度和留言 -->

            <div class="border-border/50 mt-3 border-t">
              <div
                class="text-muted-foreground flex items-center justify-end text-xs"
              >
                <div class="flex items-center space-x-4">
                  <span
                    v-if="item.uploadSpeed"
                    class="text-muted-foreground flex items-center gap-1 text-xs"
                  >
                    <Upload theme="outline" size="12" fill="currentColor" />
                    {{ item.uploadSpeed }}
                  </span>
                  <span>共 {{ item.files.length }} 个文件</span>
                  <span>总计 {{ formatFileSize(item.totalSize) }}</span>
                  <!-- 分享码显示 -->
                  <div
                    v-if="item.status === 'success'"
                    class="flex items-center"
                  >
                    <!-- <span class="text-xs font-medium text-primary-600">
                      分享码
                    </span> -->

                    <Tooltip
                      content="点击复制分享码"
                      placement="top"
                      :delay="500"
                      :disabled="!item.shareCode"
                    >
                      <Button
                        size="small"
                        appearance="transparent"
                        @click="copyShareCode(item.shareCode)"
                        class="hover:bg-primary-100 dark:hover:bg-primary-50/20 rounded-xl p-1"
                      >
                        <span
                          class="border-primary-200 bg-primary-50 text-primary-700 dark:border-primary-700 dark:bg-primary-50/10 dark:text-primary-300 rounded border px-2 py-0.5 font-mono text-lg"
                        >
                          {{ item.shareCode }}
                        </span>
                        <div
                          class="ml-1 mr-1 flex flex-shrink-0 items-center justify-center"
                        >
                          <Code
                            theme="outline"
                            size="14"
                            fill="currentColor"
                            class="text-primary-600"
                          />
                        </div>
                      </Button>
                    </Tooltip>
                  </div>
                </div>

                <!-- 总体进度（仅对正在上传的显示） -->
                <div
                  v-if="item.status === 'uploading' && item.totalProgress"
                  class="flex items-center space-x-2"
                >
                  <span class="text-blue-600">
                    总进度：{{ item.totalProgress }}%
                  </span>
                </div>
              </div>

              <p v-if="item.message" class="mt-2 text-xs text-blue-600">
                留言：{{ item.message }}
              </p>
            </div>
          </div>
        </div>
      </div>

      <!-- 上传对话框 -->
      <UploadDialog
        ref="uploadDialogRef"
        @upload-complete="handleDialogUploadComplete"
        @close="closeUploadDialog"
        @is-upload-change="(v) => (isUploading = v)"
        v-model:is-open="isUploadDialogOpen"
      />

      <!-- 消息编辑对话框 -->
      <MessageEditDialog
        v-model="isMessageDialogOpen"
        :current-upload-item-id="currentUploadItemId"
        :current-share-code="currentShareCode"
        :current-edit-token="currentEditToken"
        @messages-updated="handleMessagesUpdated"
        @close="closeMessageDialog"
      />

      <!-- 分享详情对话框 -->
      <ShareInfoDialog
        v-model="isShareInfoDialogOpen"
        :share-info="currentShareInfo"
        @close="closeShareInfoDialog"
        @download-all="handleDownloadAll"
        @download-file="handleDownloadFile"
      />

      <!-- 上传完成对话框 -->
      <UploadCompleteDialog
        v-model:is-open="isUploadCompleteDialogOpen"
        :upload-items="uploadCompleteData.items"
        :share-code="uploadCompleteData.shareCode"
        :average-speed="uploadCompleteData.averageSpeed"
        :total-size="uploadCompleteData.totalSize"
        @close="closeUploadCompleteDialog"
        @view-details="handleViewDetailsFromComplete"
      />
    </div>
  </div>
</template>

<style scoped>
/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: var(--background);
}

::-webkit-scrollbar-thumb {
  background: var(--border);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: var(--primary);
}

/* 进度条动画 */
@keyframes pulse {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}

.uploading-item {
  animation: pulse 2s infinite;
}
</style>
